#include "userordertestwindow.h"
#include <QComboBox>
#include <QDebug>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QMessageBox>
#include <QPalette>
#include <QPushButton>
#include <QScrollArea>
#include <QStackedWidget>
#include <QVBoxLayout>
#include <QWidget>
#include "flightinfo.h"
#include "interfacemanager.h"
#include "logwindow.h"
#include "myframe.h"
#include "order.h"
#include "system.h"
#include "ui_userordertestwindow.h"

//碎碎念,希望可以把数据库中订单的出发时间和到达时间的秒数位删掉;
//支付以后需要将数据库中的状态order_status修改为paid
//取消订单界面确认弹窗中没法去除黑框，这个ui我真的改不明白

void fetchOrdersByUserId(int userId, QList<Order> &orders)
{
    orders.clear();

    QNetworkAccessManager manager;
    QUrl url("http://127.0.0.1:8080/api/orders/search"); // API 的实际地址

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求数据
    QJsonObject json;
    json["user_id"] = LogWindow::userId; // 根据用户ID查询订单信息
    qDebug() << "userid:" << LogWindow::userId;

    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager.post(request, requestData);

    // 阻塞式等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 检查请求是否成功
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Request failed: " << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 获取返回的 JSON 数据
    QByteArray responseData = reply->readAll();
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);

    if (responseDoc.isObject()) {
        QJsonObject responseObj = responseDoc.object();
        int code = responseObj["code"].toInt();
        QString message = responseObj["message"].toString();

        if (code == 200) {
            // 订单查询成功，处理返回的数据
            QJsonArray ordersArray = responseObj["data"].toArray();

            if (!ordersArray.isEmpty()) {
                // 处理每一笔订单
                for (const QJsonValue &value : ordersArray) {
                    QJsonObject orderObj = value.toObject();
                    int orderId = orderObj["id"].toInt();
                    QString flightId = orderObj["flight_id"].toString();
                    QString seatType = orderObj["seat_type"].toString();
                    double price = orderObj["price"].toDouble();
                    QString orderStatus = orderObj["order_status"].toString();
                    QDateTime paymentTime
                        = QDateTime::fromString(orderObj["payment_time"].toString(), Qt::ISODate);
                    QDateTime refundTime = QDateTime::fromString(orderObj["refund_time"].toString(),
                                                                 Qt::ISODate);
                    QDateTime createdAt = QDateTime::fromString(orderObj["created_at"].toString(),
                                                                Qt::ISODate);

                    // 获取航班信息，假设 API 返回航班相关的详细信息
                    QJsonObject flightObj = orderObj["flight_info"].toObject();
                    QString flightNumber = flightObj["flight_number"].toString();
                    QString departure = flightObj["departure"].toString();
                    QString destination = flightObj["destination"].toString();
                    QString departureAirport = flightObj["departure_airport"].toString();
                    QString destinationAirport = flightObj["destination_airport"].toString();
                    QDateTime departureTime
                        = QDateTime::fromString(flightObj["departure_time"].toString(), Qt::ISODate);
                    QDateTime arrivalTime
                        = QDateTime::fromString(flightObj["arrival_time"].toString(), Qt::ISODate);
                    QString airlineCompany = flightObj["airline_company"].toString();
                    QString aircraftModel = flightObj["aircraft_model"].toString();

                    // 创建 FlightInfo 对象
                    FlightInfo flightInfo(flightNumber,
                                          departure,
                                          destination,
                                          departureAirport,
                                          destinationAirport,
                                          departureTime,
                                          arrivalTime,
                                          airlineCompany,
                                          aircraftModel);

                    // 创建 Order 对象并加入列表
                    orders.append(Order(orderId,
                                        flightId,
                                        seatType,
                                        price,
                                        orderStatus,
                                        paymentTime,
                                        refundTime,
                                        createdAt,
                                        flightInfo));
                }

                // 输出查询到的订单信息
                for (const Order &order : orders) {
                    order.printOrder(); // 打印每个订单的详细信息
                }
            }
        } else {
            qDebug() << "Error: " << message;
        }
    } else {
        qDebug() << "Failed to parse JSON response.";
    }

    reply->deleteLater();
}

void fetchOrdersByUserId_2(int userId, QList<Order> &orders2)
{
    orders2.clear();

    QNetworkAccessManager manager;
    QUrl url("http://127.0.0.1:8080/api/orders/search");

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求数据
    QJsonObject json;
    json["user_id"] = userId;
    json["order_status"] = "Unpaid"; // 添加筛选条件：仅查询未支付的订单

    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager.post(request, requestData);

    // 阻塞式等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 检查请求是否成功
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Request failed: " << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 获取返回的 JSON 数据
    QByteArray responseData = reply->readAll();
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);

    if (responseDoc.isObject()) {
        QJsonObject responseObj = responseDoc.object();
        int code = responseObj["code"].toInt();
        QString message = responseObj["message"].toString();

        if (code == 200) {
            // 订单查询成功，处理返回的数据
            QJsonArray ordersArray = responseObj["data"].toArray();

            if (!ordersArray.isEmpty()) {
                // 处理每一笔订单
                for (const QJsonValue &value : ordersArray) {
                    QJsonObject orderObj = value.toObject();
                    QString orderStatus = orderObj["order_status"].toString();

                    // 仅处理未支付的订单
                    if (orderStatus == "Unpaid") {
                        int orderId = orderObj["id"].toInt();
                        QString flightId = orderObj["flight_id"].toString();
                        QString seatType = orderObj["seat_type"].toString();
                        double price = orderObj["price"].toDouble();
                        QDateTime paymentTime
                            = QDateTime::fromString(orderObj["payment_time"].toString(),
                                                    Qt::ISODate);
                        QDateTime refundTime
                            = QDateTime::fromString(orderObj["refund_time"].toString(), Qt::ISODate);
                        QDateTime createdAt
                            = QDateTime::fromString(orderObj["created_at"].toString(), Qt::ISODate);

                        // 获取航班信息
                        QJsonObject flightObj = orderObj["flight_info"].toObject();
                        QString flightNumber = flightObj["flight_number"].toString();
                        QString departure = flightObj["departure"].toString();
                        QString destination = flightObj["destination"].toString();
                        QString departureAirport = flightObj["departure_airport"].toString();
                        QString destinationAirport = flightObj["destination_airport"].toString();
                        QDateTime departureTime
                            = QDateTime::fromString(flightObj["departure_time"].toString(),
                                                    Qt::ISODate);
                        QDateTime arrivalTime
                            = QDateTime::fromString(flightObj["arrival_time"].toString(),
                                                    Qt::ISODate);
                        QString airlineCompany = flightObj["airline_company"].toString();
                        QString aircraftModel = flightObj["aircraft_model"].toString();

                        // 创建 FlightInfo 对象
                        FlightInfo flightInfo(flightNumber,
                                              departure,
                                              destination,
                                              departureAirport,
                                              destinationAirport,
                                              departureTime,
                                              arrivalTime,
                                              airlineCompany,
                                              aircraftModel);

                        // 创建 Order 对象并加入列表
                        orders2.append(Order(orderId,
                                             flightId,
                                             seatType,
                                             price,
                                             orderStatus,
                                             paymentTime,
                                             refundTime,
                                             createdAt,
                                             flightInfo));
                    }
                }

                // 输出查询到的未支付订单信息
                for (const Order &order : orders2) {
                    order.printOrder(); // 打印每个订单的详细信息
                }
            }
        } else {
            qDebug() << "Error: " << message;
        }
    } else {
        qDebug() << "Failed to parse JSON response.";
    }

    reply->deleteLater();
}

void fetchOrdersByUserId_3(int userId, QList<Order> &orders3)
{
    orders3.clear();

    QNetworkAccessManager manager;
    QUrl url("http://127.0.0.1:8080/api/orders/search");

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求数据
    QJsonObject json;
    json["user_id"] = userId;

    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager.post(request, requestData);

    // 阻塞式等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 检查请求是否成功
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Request failed: " << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 获取返回的 JSON 数据
    QByteArray responseData = reply->readAll();
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);

    if (responseDoc.isObject()) {
        QJsonObject responseObj = responseDoc.object();
        int code = responseObj["code"].toInt();
        QString message = responseObj["message"].toString();

        if (code == 200) {
            // 订单查询成功，处理返回的数据
            QJsonArray ordersArray = responseObj["data"].toArray();

            if (!ordersArray.isEmpty()) {
                // 获取当前时间
                QDateTime currentTime = QDateTime::currentDateTime();

                // 处理每一笔订单
                for (const QJsonValue &value : ordersArray) {
                    QJsonObject orderObj = value.toObject();
                    QString orderStatus = orderObj["order_status"].toString();
                    QJsonObject flightObj = orderObj["flight_info"].toObject();

                    // 获取航班的出发时间
                    QDateTime departureTime
                        = QDateTime::fromString(flightObj["departure_time"].toString(), Qt::ISODate);

                    // 仅处理出发时间晚于当前时间的订单
                    if (departureTime > currentTime) {
                        int orderId = orderObj["id"].toInt();
                        QString flightId = orderObj["flight_id"].toString();
                        QString seatType = orderObj["seat_type"].toString();
                        double price = orderObj["price"].toDouble();
                        QDateTime paymentTime
                            = QDateTime::fromString(orderObj["payment_time"].toString(),
                                                    Qt::ISODate);
                        QDateTime refundTime
                            = QDateTime::fromString(orderObj["refund_time"].toString(), Qt::ISODate);
                        QDateTime createdAt
                            = QDateTime::fromString(orderObj["created_at"].toString(), Qt::ISODate);

                        // 获取航班信息
                        QString flightNumber = flightObj["flight_number"].toString();
                        QString departure = flightObj["departure"].toString();
                        QString destination = flightObj["destination"].toString();
                        QString departureAirport = flightObj["departure_airport"].toString();
                        QString destinationAirport = flightObj["destination_airport"].toString();
                        QDateTime arrivalTime
                            = QDateTime::fromString(flightObj["arrival_time"].toString(),
                                                    Qt::ISODate);
                        QString airlineCompany = flightObj["airline_company"].toString();
                        QString aircraftModel = flightObj["aircraft_model"].toString();

                        // 创建 FlightInfo 对象
                        FlightInfo flightInfo(flightNumber,
                                              departure,
                                              destination,
                                              departureAirport,
                                              destinationAirport,
                                              departureTime,
                                              arrivalTime,
                                              airlineCompany,
                                              aircraftModel);

                        // 创建 Order 对象并加入列表
                        orders3.append(Order(orderId,
                                             flightId,
                                             seatType,
                                             price,
                                             orderStatus,
                                             paymentTime,
                                             refundTime,
                                             createdAt,
                                             flightInfo));
                    }
                }

                // 输出查询到的出发时间晚于当前时间的订单信息
                for (const Order &order : orders3) {
                    order.printOrder(); // 打印每个订单的详细信息
                }
            }
        } else {
            qDebug() << "Error: " << message;
        }
    } else {
        qDebug() << "Failed to parse JSON response.";
    }

    reply->deleteLater();
}

void fetchOrdersByIdAndFlightNumber(int userId, QString flightNumber, QList<Order> &orders)
{
    // 清空传入的 orders 列表
    orders.clear();

    QNetworkAccessManager manager;
    QUrl url("http://127.0.0.1:8080/api/orders/search"); // API 的实际地址

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求数据
    QJsonObject json;
    json["user_id"] = userId;             // 根据用户ID查询订单信息
    json["flight_number"] = flightNumber; // 根据航班号查询订单

    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager.post(request, requestData);

    // 阻塞式等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 检查请求是否成功
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Request failed: " << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 获取返回的 JSON 数据
    QByteArray responseData = reply->readAll();
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);

    if (responseDoc.isObject()) {
        QJsonObject responseObj = responseDoc.object();
        int code = responseObj["code"].toInt();
        QString message = responseObj["message"].toString();

        if (code == 200) {
            // 订单查询成功，处理返回的数据
            QJsonArray ordersArray = responseObj["data"].toArray();

            if (!ordersArray.isEmpty()) {
                // 处理每一笔订单
                for (const QJsonValue &value : ordersArray) {
                    QJsonObject orderObj = value.toObject();
                    QString flightNumberFromResponse
                        = orderObj["flight_info"].toObject()["flight_number"].toString();

                    // 仅当返回的航班号与传入的航班号匹配时，才处理该订单
                    if (flightNumberFromResponse == flightNumber) {
                        int orderId = orderObj["id"].toInt(); // 获取返回的订单ID
                        QString flightId = orderObj["flight_id"].toString();
                        QString seatType = orderObj["seat_type"].toString();
                        double price = orderObj["price"].toDouble();
                        QString orderStatus = orderObj["order_status"].toString();
                        QDateTime paymentTime
                            = QDateTime::fromString(orderObj["payment_time"].toString(),
                                                    Qt::ISODate);
                        QDateTime refundTime
                            = QDateTime::fromString(orderObj["refund_time"].toString(), Qt::ISODate);
                        QDateTime createdAt
                            = QDateTime::fromString(orderObj["created_at"].toString(), Qt::ISODate);

                        // 获取航班信息
                        QJsonObject flightObj = orderObj["flight_info"].toObject();
                        QString departure = flightObj["departure"].toString();
                        QString destination = flightObj["destination"].toString();
                        QString departureAirport = flightObj["departure_airport"].toString();
                        QString destinationAirport = flightObj["destination_airport"].toString();
                        QDateTime departureTime
                            = QDateTime::fromString(flightObj["departure_time"].toString(),
                                                    Qt::ISODate);
                        QDateTime arrivalTime
                            = QDateTime::fromString(flightObj["arrival_time"].toString(),
                                                    Qt::ISODate);
                        QString airlineCompany = flightObj["airline_company"].toString();
                        QString aircraftModel = flightObj["aircraft_model"].toString();

                        // 创建 FlightInfo 对象
                        FlightInfo flightInfo(flightNumberFromResponse,
                                              departure,
                                              destination,
                                              departureAirport,
                                              destinationAirport,
                                              departureTime,
                                              arrivalTime,
                                              airlineCompany,
                                              aircraftModel);

                        // 创建 Order 对象并加入列表
                        orders.append(Order(orderId,
                                            flightId,
                                            seatType,
                                            price,
                                            orderStatus,
                                            paymentTime,
                                            refundTime,
                                            createdAt,
                                            flightInfo));
                    }
                }

                // 输出查询到的订单信息
                for (const Order &order : orders) {
                    order.printOrder(); // 打印每个订单的详细信息
                }
            }
        } else {
            qDebug() << "Error: " << message;
        }
    } else {
        qDebug() << "Failed to parse JSON response.";
    }

    reply->deleteLater();
}

void fetchOrdersByUserIdAndDateRange(int userId,
                                     const QDateTime &startDate,
                                     const QDateTime &endDate,
                                     QList<Order> &orders)
{
    orders.clear();

    QNetworkAccessManager manager;
    QUrl url("http://127.0.0.1:8080/api/orders/search"); // API 的实际地址

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求数据
    QJsonObject json;
    json["user_id"] = userId; // 根据用户ID查询订单信息

    // 添加出发时间范围筛选
    json["departure_start"] = startDate.toString(Qt::ISODate); // 起始出发时间
    json["departure_end"] = endDate.toString(Qt::ISODate);     // 结束出发时间

    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    // 发送 POST 请求
    QNetworkReply *reply = manager.post(request, requestData);

    // 阻塞式等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 检查请求是否成功
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Request failed: " << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 获取返回的 JSON 数据
    QByteArray responseData = reply->readAll();
    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);

    if (responseDoc.isObject()) {
        QJsonObject responseObj = responseDoc.object();
        int code = responseObj["code"].toInt();
        QString message = responseObj["message"].toString();

        if (code == 200) {
            // 订单查询成功，处理返回的数据
            QJsonArray ordersArray = responseObj["data"].toArray();

            if (!ordersArray.isEmpty()) {
                // 处理每一笔订单
                for (const QJsonValue &value : ordersArray) {
                    QJsonObject orderObj = value.toObject();
                    int orderId = orderObj["id"].toInt();
                    QString flightId = orderObj["flight_id"].toString();
                    QString seatType = orderObj["seat_type"].toString();
                    double price = orderObj["price"].toDouble();
                    QString orderStatus = orderObj["order_status"].toString();
                    QDateTime paymentTime
                        = QDateTime::fromString(orderObj["payment_time"].toString(), Qt::ISODate);
                    QDateTime refundTime = QDateTime::fromString(orderObj["refund_time"].toString(),
                                                                 Qt::ISODate);
                    QDateTime createdAt = QDateTime::fromString(orderObj["created_at"].toString(),
                                                                Qt::ISODate);

                    // 获取航班信息，假设 API 返回航班相关的详细信息
                    QJsonObject flightObj = orderObj["flight_info"].toObject();
                    QString flightNumber = flightObj["flight_number"].toString();
                    QString departure = flightObj["departure"].toString();
                    QString destination = flightObj["destination"].toString();
                    QString departureAirport = flightObj["departure_airport"].toString();
                    QString destinationAirport = flightObj["destination_airport"].toString();
                    QDateTime departureTime
                        = QDateTime::fromString(flightObj["departure_time"].toString(), Qt::ISODate);
                    QDateTime arrivalTime
                        = QDateTime::fromString(flightObj["arrival_time"].toString(), Qt::ISODate);
                    QString airlineCompany = flightObj["airline_company"].toString();
                    QString aircraftModel = flightObj["aircraft_model"].toString();

                    // 判断出发时间是否在选择的时间范围内
                    if (departureTime >= startDate && departureTime <= endDate) {
                        // 创建 FlightInfo 对象
                        FlightInfo flightInfo(flightNumber,
                                              departure,
                                              destination,
                                              departureAirport,
                                              destinationAirport,
                                              departureTime,
                                              arrivalTime,
                                              airlineCompany,
                                              aircraftModel);

                        // 创建 Order 对象并加入列表
                        orders.append(Order(orderId,
                                            flightId,
                                            seatType,
                                            price,
                                            orderStatus,
                                            paymentTime,
                                            refundTime,
                                            createdAt,
                                            flightInfo));
                    }
                }

                // 输出查询到的订单信息
                for (const Order &order : orders) {
                    order.printOrder(); // 打印每个订单的详细信息
                }
            }
        } else {
            qDebug() << "Error: " << message;
        }
    } else {
        qDebug() << "Failed to parse JSON response.";
    }

    reply->deleteLater();
}

void resetScrollArea(QScrollArea *scrollArea)
{
    // 获取 scrollArea 中的当前控件
    QWidget *widget = scrollArea->widget();

    // 删除所有子控件
    if (widget) {
        // 清除子控件
        QLayout *layout = widget->layout();
        if (layout) {
            QLayoutItem *child;
            while ((child = layout->takeAt(0)) != nullptr) {
                // 删除子控件和布局项
                delete child->widget(); // 删除控件
                delete child;           // 删除布局项
            }
        }

        // 将 QScrollArea 的内容恢复到初始状态（例如：恢复一个空白或默认控件）
        // 这里可以根据实际需求恢复到一个特定的控件，比如一个空的 QWidget 或一个初始布局
        widget->setLayout(new QVBoxLayout); // 创建新的空布局
        scrollArea->setWidget(widget);      // 将空控件重新设置为 QScrollArea 的内容
    }
}

void printList(int userId, QList<Order> &orders, Ui::UserordertestWindow *ui)
{
    int num = orders.size();
    int framesPerGroup = 5; // 每组包含 5 个 MyFrame

    // 获取 QScrollArea 中的原始内容部件
    QWidget *scrollAreaWidget = ui->scrollArea->widget();
    resetScrollArea(ui->scrollArea);
    if (!scrollAreaWidget) {
        scrollAreaWidget = new QWidget;
        ui->scrollArea->setWidget(scrollAreaWidget);
    }

    if (num == 0)
        return;

    // 获取这个部件的布局，假设它是垂直布局
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout *>(scrollAreaWidget->layout());
    if (!mainLayout) {
        mainLayout = new QVBoxLayout(scrollAreaWidget);
        scrollAreaWidget->setLayout(mainLayout);
    }

    // 创建 QStackedWidget 来切换不同的组
    QStackedWidget *stackedWidget = new QStackedWidget;

    // 创建按钮布局，用来放置按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout;

    // 分组并创建每个 QScrollArea
    int groupCount = (num + framesPerGroup - 1) / framesPerGroup; // 计算组数

    // 用来记录按钮的列表，方便设置选中状态
    QList<QPushButton *> buttonList;
    ;

    // 创建按钮
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        // 创建一个新的 QScrollArea
        QScrollArea *scrollArea = new QScrollArea;
        scrollArea->setWidgetResizable(true);

        // 创建一个新的 QWidget 来放置当前组的 MyFrame
        QWidget *groupWidget = new QWidget;
        QVBoxLayout *groupLayout = new QVBoxLayout(groupWidget);
        groupWidget->setLayout(groupLayout);

        // 设置 groupLayout 的对齐方式为顶部对齐
        groupLayout->setAlignment(Qt::AlignTop); // 这里设置布局顶部对齐

        // 将当前组的 MyFrame 添加到 groupLayout 中
        for (int i = groupIndex * framesPerGroup; i < (groupIndex + 1) * framesPerGroup && i < num;
             ++i) {
            QString flight_number = orders[i].flight_info.flight_number;
            QString type = orders[i].seat_type;
            QString price = QString::number(orders[i].price);
            QString departureTime = orders[i].flight_info.departure_time.toString();
            QString arrivalTime = orders[i].flight_info.arrival_time.toString();
            QString departureCity = orders[i].flight_info.departure;
            QString arrivalCity = orders[i].flight_info.destination;
            QString aircraftmodel = orders[i].flight_info.aircraft_model;
            QString order_status = orders[i].order_status;
            //userId是我的全局变量
            int order_id = orders[i].order_id;

            MyFrame *frame = new MyFrame(userId,
                                         order_id,
                                         flight_number,
                                         departureTime,
                                         arrivalTime,
                                         departureCity,
                                         arrivalCity,
                                         aircraftmodel,
                                         type,
                                         price,
                                         order_status);
            groupLayout->addWidget(frame);
        }

        // 将 QWidget 放入 QScrollArea 中
        scrollArea->setWidget(groupWidget);

        // 将 scrollArea 添加到 QStackedWidget 中
        stackedWidget->addWidget(scrollArea);

        // 为每个组创建一个按钮
        QPushButton *button = new QPushButton(QString("Page %1").arg(groupIndex + 1));
        buttonList.append(button); // 添加到按钮列表

        // 设置按钮的固定大小（宽度为100，高度为40）
        button->setFixedSize(100, 40);

        // 设置按钮的初始样式
        button->setStyleSheet("background-color: orange;");

        // 添加按钮到布局
        buttonLayout->addWidget(button);
    }
    // 在for循环外部连接按钮的点击事件
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        QPushButton *button = buttonList[groupIndex];

        // 使用值捕获'groupIndex'，避免捕获引用
        MyFrame::connect(button,
                         &QPushButton::clicked,
                         [stackedWidget, groupIndex, buttonList, button]() {
                             // 空指针检查
                             if (!stackedWidget) {
                                 qWarning() << "stackedWidget is null!";
                                 return;
                             }

                             // 切换页面
                             stackedWidget->setCurrentIndex(groupIndex);

                             // 修改按钮背景色，恢复所有按钮的默认样式
                             for (QPushButton *btn : buttonList) {
                                 btn->setStyleSheet("background-color: orange;");
                             }

                             // 修改当前按钮的背景色
                             button->setStyleSheet("background-color: lightblue;");
                         });
    }

    // 创建一个容器 widget 用来放置按钮和 stackedWidget
    QWidget *containerWidget = new QWidget;
    QVBoxLayout *containerLayout = new QVBoxLayout(containerWidget);

    // 将 QStackedWidget 添加到容器布局中
    containerLayout->addWidget(stackedWidget);

    // 将按钮布局添加到容器中
    containerLayout->addLayout(buttonLayout);

    // 设置主界面的布局
    mainLayout->addWidget(containerWidget);
}

void printList_2(int userId, QList<Order> &orders, Ui::UserordertestWindow *ui)
{
    int num = orders.size();
    int framesPerGroup = 5; // 每组包含 5 个 MyFrame

    // 获取 QScrollArea 中的原始内容部件
    QWidget *scrollAreaWidget = ui->scrollArea_2->widget();
    resetScrollArea(ui->scrollArea_2);
    if (!scrollAreaWidget) {
        scrollAreaWidget = new QWidget;
        ui->scrollArea_2->setWidget(scrollAreaWidget);
    }

    if (num == 0)
        return;

    // 获取这个部件的布局，假设它是垂直布局
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout *>(scrollAreaWidget->layout());
    if (!mainLayout) {
        mainLayout = new QVBoxLayout(scrollAreaWidget);
        scrollAreaWidget->setLayout(mainLayout);
    }

    // 创建 QStackedWidget 来切换不同的组
    QStackedWidget *stackedWidget = new QStackedWidget;

    // 创建按钮布局，用来放置按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout;

    // 分组并创建每个 QScrollArea
    int groupCount = (num + framesPerGroup - 1) / framesPerGroup; // 计算组数

    // 用来记录按钮的列表，方便设置选中状态
    QList<QPushButton *> buttonList;
    ;

    // 创建按钮
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        // 创建一个新的 QScrollArea
        QScrollArea *scrollArea = new QScrollArea;
        scrollArea->setWidgetResizable(true);

        // 创建一个新的 QWidget 来放置当前组的 MyFrame
        QWidget *groupWidget = new QWidget;
        QVBoxLayout *groupLayout = new QVBoxLayout(groupWidget);
        groupWidget->setLayout(groupLayout);

        // 设置 groupLayout 的对齐方式为顶部对齐
        groupLayout->setAlignment(Qt::AlignTop); // 这里设置布局顶部对齐

        // 将当前组的 MyFrame 添加到 groupLayout 中
        for (int i = groupIndex * framesPerGroup; i < (groupIndex + 1) * framesPerGroup && i < num;
             ++i) {
            QString flight_number = orders[i].flight_info.flight_number;
            QString type = orders[i].seat_type;
            QString price = QString::number(orders[i].price);
            QString departureTime = orders[i].flight_info.departure_time.toString();
            QString arrivalTime = orders[i].flight_info.arrival_time.toString();
            QString departureCity = orders[i].flight_info.departure;
            QString arrivalCity = orders[i].flight_info.destination;
            QString aircraftmodel = orders[i].flight_info.aircraft_model;
            QString order_status = orders[i].order_status;
            //userId是我的全局变量
            int order_id = orders[i].order_id;

            MyFrame *frame = new MyFrame(userId,
                                         order_id,
                                         flight_number,
                                         departureTime,
                                         arrivalTime,
                                         departureCity,
                                         arrivalCity,
                                         aircraftmodel,
                                         type,
                                         price,
                                         order_status);
            groupLayout->addWidget(frame);
        }

        // 将 QWidget 放入 QScrollArea 中
        scrollArea->setWidget(groupWidget);

        // 将 scrollArea 添加到 QStackedWidget 中
        stackedWidget->addWidget(scrollArea);

        // 为每个组创建一个按钮
        QPushButton *button = new QPushButton(QString("Page %1").arg(groupIndex + 1));
        buttonList.append(button); // 添加到按钮列表

        // 设置按钮的固定大小（宽度为100，高度为40）
        button->setFixedSize(100, 40);

        // 设置按钮的初始样式
        button->setStyleSheet("background-color: orange;");

        // 添加按钮到布局
        buttonLayout->addWidget(button);
    }
    // 在for循环外部连接按钮的点击事件
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        QPushButton *button = buttonList[groupIndex];

        // 使用值捕获'groupIndex'，避免捕获引用
        MyFrame::connect(button,
                         &QPushButton::clicked,
                         [stackedWidget, groupIndex, buttonList, button]() {
                             // 空指针检查
                             if (!stackedWidget) {
                                 qWarning() << "stackedWidget is null!";
                                 return;
                             }

                             // 切换页面
                             stackedWidget->setCurrentIndex(groupIndex);

                             // 修改按钮背景色，恢复所有按钮的默认样式
                             for (QPushButton *btn : buttonList) {
                                 btn->setStyleSheet("background-color: orange;");
                             }

                             // 修改当前按钮的背景色
                             button->setStyleSheet("background-color: lightblue;");
                         });
    }

    // 创建一个容器 widget 用来放置按钮和 stackedWidget
    QWidget *containerWidget = new QWidget;
    QVBoxLayout *containerLayout = new QVBoxLayout(containerWidget);

    // 将 QStackedWidget 添加到容器布局中
    containerLayout->addWidget(stackedWidget);

    // 将按钮布局添加到容器中
    containerLayout->addLayout(buttonLayout);

    // 设置主界面的布局
    mainLayout->addWidget(containerWidget);
}

void printList_3(int userId, QList<Order> &orders, Ui::UserordertestWindow *ui)
{
    int num = orders.size();
    int framesPerGroup = 5; // 每组包含 5 个 MyFrame

    // 获取 QScrollArea 中的原始内容部件
    QWidget *scrollAreaWidget = ui->scrollArea_3->widget();
    resetScrollArea(ui->scrollArea_3);
    if (!scrollAreaWidget) {
        scrollAreaWidget = new QWidget;
        ui->scrollArea_3->setWidget(scrollAreaWidget);
    }

    if (num == 0)
        return;

    // 获取这个部件的布局，假设它是垂直布局
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout *>(scrollAreaWidget->layout());
    if (!mainLayout) {
        mainLayout = new QVBoxLayout(scrollAreaWidget);
        scrollAreaWidget->setLayout(mainLayout);
    }

    // 创建 QStackedWidget 来切换不同的组
    QStackedWidget *stackedWidget = new QStackedWidget;

    // 创建按钮布局，用来放置按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout;

    // 分组并创建每个 QScrollArea
    int groupCount = (num + framesPerGroup - 1) / framesPerGroup; // 计算组数

    // 用来记录按钮的列表，方便设置选中状态
    QList<QPushButton *> buttonList;
    ;

    // 创建按钮
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        // 创建一个新的 QScrollArea
        QScrollArea *scrollArea = new QScrollArea;
        scrollArea->setWidgetResizable(true);

        // 创建一个新的 QWidget 来放置当前组的 MyFrame
        QWidget *groupWidget = new QWidget;
        QVBoxLayout *groupLayout = new QVBoxLayout(groupWidget);
        groupWidget->setLayout(groupLayout);

        // 设置 groupLayout 的对齐方式为顶部对齐
        groupLayout->setAlignment(Qt::AlignTop); // 这里设置布局顶部对齐

        // 将当前组的 MyFrame 添加到 groupLayout 中
        for (int i = groupIndex * framesPerGroup; i < (groupIndex + 1) * framesPerGroup && i < num;
             ++i) {
            QString flight_number = orders[i].flight_info.flight_number;
            QString type = orders[i].seat_type;
            QString price = QString::number(orders[i].price);
            QString departureTime = orders[i].flight_info.departure_time.toString();
            QString arrivalTime = orders[i].flight_info.arrival_time.toString();
            QString departureCity = orders[i].flight_info.departure;
            QString arrivalCity = orders[i].flight_info.destination;
            QString aircraftmodel = orders[i].flight_info.aircraft_model;
            QString orderstatus = orders[i].order_status;
            //userId是我的全局变量
            int order_id = orders[i].order_id;

            MyFrame *frame = new MyFrame(userId,
                                         order_id,
                                         flight_number,
                                         departureTime,
                                         arrivalTime,
                                         departureCity,
                                         arrivalCity,
                                         aircraftmodel,
                                         type,
                                         price,
                                         orderstatus);
            groupLayout->addWidget(frame);
        }

        // 将 QWidget 放入 QScrollArea 中
        scrollArea->setWidget(groupWidget);

        // 将 scrollArea 添加到 QStackedWidget 中
        stackedWidget->addWidget(scrollArea);

        // 为每个组创建一个按钮
        QPushButton *button = new QPushButton(QString("Page %1").arg(groupIndex + 1));
        buttonList.append(button); // 添加到按钮列表

        // 设置按钮的固定大小（宽度为100，高度为40）
        button->setFixedSize(100, 40);

        // 设置按钮的初始样式
        button->setStyleSheet("background-color: orange;");

        // 添加按钮到布局
        buttonLayout->addWidget(button);
    }
    // 在for循环外部连接按钮的点击事件
    for (int groupIndex = 0; groupIndex < groupCount; ++groupIndex) {
        QPushButton *button = buttonList[groupIndex];

        // 使用值捕获'groupIndex'，避免捕获引用
        MyFrame::connect(button,
                         &QPushButton::clicked,
                         [stackedWidget, groupIndex, buttonList, button]() {
                             // 空指针检查
                             if (!stackedWidget) {
                                 qWarning() << "stackedWidget is null!";
                                 return;
                             }

                             // 切换页面
                             stackedWidget->setCurrentIndex(groupIndex);

                             // 修改按钮背景色，恢复所有按钮的默认样式
                             for (QPushButton *btn : buttonList) {
                                 btn->setStyleSheet("background-color: orange;");
                             }

                             // 修改当前按钮的背景色
                             button->setStyleSheet("background-color: lightblue;");
                         });
    }

    // 创建一个容器 widget 用来放置按钮和 stackedWidget
    QWidget *containerWidget = new QWidget;
    QVBoxLayout *containerLayout = new QVBoxLayout(containerWidget);

    // 将 QStackedWidget 添加到容器布局中
    containerLayout->addWidget(stackedWidget);

    // 将按钮布局添加到容器中
    containerLayout->addLayout(buttonLayout);

    // 设置主界面的布局
    mainLayout->addWidget(containerWidget);
}

QList<Order> orders;   //全部订单或被筛选后的订单
QList<Order> orders_2; //未支付的订单
QList<Order> orders_3; //未出行的订单
int userId = 1;

UserordertestWindow::UserordertestWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::UserordertestWindow)
{
    ui->setupUi(this);

    // 连接信号与槽
    connect(this,
            &UserordertestWindow::pushButton5Clicked,
            this,
            &UserordertestWindow::on_pushButton_5_clicked);

    ui->dateEdit->setDate(QDate::currentDate()); //设置dateEdit中的时间为当天时间
    ui->dateEdit_2->setDate(QDate::currentDate());

    // 获取 UI 中的 QComboBox
    QComboBox *comboBox = ui->comboBox;

    // 添加选项
    comboBox->addItem("全部订单");
    comboBox->addItem("机票");
    comboBox->addItem("签证");
    comboBox->addItem("机+酒");
    comboBox->addItem("门票");

    // 插入一个分割线
    comboBox->insertSeparator(comboBox->count());

    comboBox->addItem("礼品卡");
    comboBox->addItem("外币兑换");

    // 获取 ui 中的 QListWidget
    QListWidget *listWidget = ui->listWidget;

    // 添加一些简单的项
    listWidget->addItem("首页");
    listWidget->addItem("订单");
    listWidget->addItem("消息");
    listWidget->addItem("个人中心");

    // 创建一个带有按钮的列表项
    QListWidgetItem *itemWithButton = new QListWidgetItem("Item with button");
    QPushButton *button = new QPushButton("Click Me");

    // 将按钮添加到列表项中
    listWidget->setItemWidget(itemWithButton, button);

    // 按钮点击事件
    connect(button, &QPushButton::clicked, this, []() { qDebug() << "Button in Item clicked!"; });

    // 如果需要其他交互，比如点击项事件：
    connect(listWidget, &QListWidget::itemClicked, this, [this](QListWidgetItem *item) {
        if (item->text() == "首页") {
            qDebug() << "点击了首页项！";
            InterfaceManager::instance()->switchToPage("/MainWindow/First/FlightCheck");
        } else if (item->text() == "订单") {
            qDebug() << "点击了订单项！";
            // 处理点击“订单”项时的逻辑
        } else if (item->text() == "消息") {
            qDebug() << "点击了消息项！";
            // 处理点击“消息”项时的逻辑
        } else if (item->text() == "个人中心") {
            qDebug() << "点击了个人中心项！";
            // 处理点击“个人中心”项时的逻辑
        }
    });

    // 设置头像圆形图片
    QString imagePath = ":/Photo/Photos/Profile.jpg";
    setRoundedImage(ui->Profile, imagePath);

    fetchOrdersByUserId(userId, orders);
    printList(userId, orders, ui);

    fetchOrdersByUserId_2(userId, orders_2);
    printList_2(userId, orders_2, ui);

    fetchOrdersByUserId_3(userId, orders_3);
    printList_3(userId, orders_3, ui);
}

UserordertestWindow::~UserordertestWindow()
{
    delete ui;
}

void UserordertestWindow::on_pushButton_2_clicked()
{
    InterfaceManager::instance()->switchToPage("/MainWindow/First/FlightCheck");
}

//这里是一个查询按钮
void UserordertestWindow::
    on_pushButton_4_clicked() //只要订单号不为空就按照订单号进行搜索，若订单号为空就按照日期进行搜索
{
    // 获取输入的订单号
    QString inputText = ui->ordernumber_inquiry->text();

    if (!inputText.isEmpty()) {
        fetchOrdersByIdAndFlightNumber(userId, inputText, orders);
        printList(userId, orders, ui);
        if (orders.size() == 0) {
            QMessageBox::information(ui->centralwidget, "提示", "订单号不存在", QMessageBox::Ok);
        }
    } else {
        QDateTime startDate = ui->dateEdit->dateTime();
        QDateTime endDate = ui->dateEdit_2->dateTime();
        fetchOrdersByUserIdAndDateRange(userId, startDate, endDate, orders);
        printList(userId, orders, ui);
    }
}

//这里是一个重置查询按钮
void UserordertestWindow::on_pushButton_5_clicked()
{
    qDebug() << "进入了重置按钮";
    ui->ordernumber_inquiry->setText("");
    ui->dateEdit->setDate(QDate::currentDate()); //设置dateEdit中的时间为当天时间
    ui->dateEdit_2->setDate(QDate::currentDate());
    fetchOrdersByUserId(userId, orders);

    fetchOrdersByUserId(userId, orders);
    printList(userId, orders, ui);

    fetchOrdersByUserId_2(userId, orders_2);
    printList_2(userId, orders_2, ui);

    fetchOrdersByUserId_3(userId, orders_3);
    printList_3(userId, orders_3, ui);
    this->update(); // 强制刷新当前窗口
}
